<template>
  <div class="p-2">
    <el-card shadow="hover">
      <label class="label">监控总览</label>

      <div style="margin-top: 20px; display: flex; padding-left: 20px">
        <div style="height: 62px; width: 220px; display: flex; align-items: center">
          <el-image :src="circleCameraUrl" fit="contain" style="width: 62px; height: 62px" />
          <div style="width: 140px; margin-left: 6px">
            <p style="margin: 0; font-weight: 400; font-size: 18px; color: #666666">接入总数</p>
            <p style="margin: 0; font-weight: bold; font-size: 30px; color: #255ee5">{{ equipmentStatistic.totalCount }}</p>
          </div>
        </div>
        <div style="height: 62px; width: 220px; display: flex; align-items: center">
          <el-image :src="circleSuccessUrl" fit="contain" style="width: 62px; height: 62px" />
          <div style="width: 140px; margin-left: 6px">
            <p style="margin: 0; font-weight: 400; font-size: 18px; color: #666666">在线个数</p>
            <p style="margin: 0; font-weight: bold; font-size: 30px; color: #255ee5">{{ equipmentStatistic.onlineCount }}</p>
          </div>
        </div>
        <div style="height: 62px; width: 220px; display: flex; align-items: center">
          <el-image :src="circleMinusUrl" fit="contain" style="width: 62px; height: 62px" />
          <div style="width: 140px; margin-left: 6px">
            <p style="margin: 0; font-weight: 400; font-size: 18px; color: #666666">离线个数</p>
            <p style="margin: 0; font-weight: bold; font-size: 30px; color: #255ee5">{{ equipmentStatistic.offlineCount }}</p>
          </div>
        </div>
      </div>
    </el-card>

    <el-card shadow="never">
      <label class="label">监控设备列表</label>

      <el-row :gutter="10" class="mb8">
        <el-col :span="22">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备分组" prop="groupId">
              <el-select v-model="queryParams.groupId" placeholder="请选择设备分组" clearable>
                <el-option v-for="item in cameraGroup" :key="item.equipmentCameraGroupId" :label="item.cameraGroupName" :value="item.equipmentCameraGroupId" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备编码" prop="equipmentCode">
              <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备类型" prop="cameraType">
              <el-select v-model="queryParams.cameraType" placeholder="请选择设备类型" clearable>
                <el-option v-for="dict in camera_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备识别码" prop="deviceId">
              <el-input v-model="queryParams.deviceId" placeholder="请输入设备识别码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="录入时间">
              <el-date-picker v-model="startEndTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div style="margin-bottom: 10px; display: flex; justify-content: flex-end; align-items: center">
        <el-button v-hasPermi="['admin']" type="primary" plain @click="openCreate">新增</el-button>
        <el-button v-hasPermi="['admin']" type="warning" plain @click="openSubscribeDevice">告警订阅设备</el-button>
        <el-button v-hasPermi="['admin']" type="warning" plain @click="openEventRecord">设备上报数据</el-button>
        <el-button v-hasPermi="['admin']" type="warning" plain @click="subscribeUserCameraChange">订阅设备变更通知</el-button>
        <el-button v-hasPermi="['admin']" v-loading="registerUrlBtnLoading" type="warning" plain @click="openRegisterUrl">编辑注册回调地址</el-button>
        <el-button v-loading="syncCameraLoading" type="primary" plain @click="handleSync">同步设备</el-button>
      </div>

      <el-table v-loading="loading" :data="cameraInfoList" @selection-change="tableSelectionChange">
        <el-table-column label="设备名称" align="center" prop="equipmentName" :min-width="150" show-overflow-tooltip />
        <el-table-column label="设备分组" align="center" prop="groupName" :min-width="100" show-overflow-tooltip />
        <el-table-column label="设备编码" align="center" prop="equipmentCode" :min-width="180" show-overflow-tooltip />
        <el-table-column label="设备识别码" align="center" prop="deviceId" :min-width="250" show-overflow-tooltip />
        <el-table-column label="摄像机类型" align="center" :min-width="100" show-overflow-tooltip >
          <template #default="scope">
            <dict-tag :options="camera_type" :value="scope.row.cameraType"/>
          </template>
        </el-table-column>
        <el-table-column label="安装位置" align="center" :min-width="180" show-overflow-tooltip >
          <template #default="scope">
            {{ getParkPositionStr(scope.row.parkBuildingName, scope.row.parkBuildingAreaName, scope.row.parkBuildingFloorName, scope.row.parkBuildingRoomName) }}
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" >
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">停用</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status == 2" type="danger">作废</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" align="center" >
          <template #default="scope">
            <el-tag v-if="scope.row.deviceStatus == 'ONLINE'" type="success">在线</el-tag>
            <el-tag v-if="scope.row.deviceStatus == 'OFFLINE'" type="warning">离线</el-tag>
            <el-tag v-if="scope.row.deviceStatus == 'ABNORMAL'" type="danger">异常</el-tag>
            <el-tag v-if="scope.row.deviceStatus == 'INACTIVE'" type="info">未激活</el-tag>
            <el-tag v-if="scope.row.deviceStatus == 'FROZEN'" type="info">冻结</el-tag>
            <el-tag v-if="scope.row.deviceStatus == 'HIBERNATE'" type="info">休眠</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="录入时间" align="center" prop="createTime" :min-width="170" show-overflow-tooltip >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}  {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" :min-width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['camera:camera-info:edit']" link type="primary" @click="openDetail(scope.row)">详情</el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['camera:camera-info:edit']" link type="primary" @click="openUpdate(scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['equipment:equipment-info:remove']" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改摄像头信息对话框 -->
    <el-drawer v-model="dialog.showUpdate" :title="dialog.title" size="900px" append-to-body destroy-on-close>
      <Update :equipment-id="selectedEquipmentId" @close="dialog.showUpdate = false" @success="getList" />
    </el-drawer>
    <el-drawer v-model="dialog.showAdd" :title="dialog.title" size="900px" append-to-body destroy-on-close>
      <Add @close="dialog.showAdd = false" @success="getList" />
    </el-drawer>

    <!-- 详情 摄像头信息对话框 -->
    <el-drawer v-model="dialog.showDetail" :title="dialog.title" size="900px" append-to-body destroy-on-close>
      <Detail :equipment-id="selectedEquipmentId" @close="dialog.showDetail = false" />
    </el-drawer>

    <!-- 注册回调地址对话框 -->
    <el-dialog v-model="dialog.showRegisterUrl" :title="dialog.title" width="660px" append-to-body destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="回调地址：" >
          <el-input v-model="registerUrl" placeholder="请输入回调地址" />
        </el-form-item>
      </el-form>

      <div style="margin-top: 30px; text-align: center">
        <el-button :loading="registerUrlBtnLoading" type="primary" @click="submitRegisterUrl">确 定</el-button>
        <el-button @click="dialog.showRegisterUrl=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备上报记录对话框 -->
    <el-dialog v-model="dialog.showEventRecord" :title="dialog.title" width="1000px" append-to-body destroy-on-close>
      <EventRecord @close="dialog.showEventRecord = false" />
    </el-dialog>

    <!-- 告警订阅设备对话框 -->
    <el-dialog v-model="dialog.showSubscribeDevice" :title="dialog.title" width="1000px" append-to-body destroy-on-close>
      <SubscribeDevice @close="dialog.showSubscribeDevice = false" />
    </el-dialog>

  </div>
</template>

<script setup name="cameraInfo" lang="ts">
import { delcameraInfo, equipmentSync, equipmentstatistic } from '@/api/security/camera/camera-info';
import { cameraInfoForm, cameraInfoQuery, cameraInfoVO } from '@/api/security/camera/camera-info/types';
import request from '@/utils/request';
import Update from '@/views/security/camera/camera-info/components/Update.vue';
import Add from '@/views/security/camera/camera-info/components/Add.vue';
import Detail from '@/views/security/camera/camera-info/components/Detail.vue';
import { stringify } from 'qs';
import { getParkPositionStr } from '@/utils/parkUtil';
import EventRecord from './components/EventRecord.vue';
import SubscribeDevice from './components/SubscribeDevice.vue';
import circleCameraUrl from '@/assets/images/circle-camera.png';
import circleSuccessUrl from '@/assets/images/circle-success.png';
import circleMinusUrl from '@/assets/images/circle-minus.png';
import { parseTime } from '@/utils/dateTime'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { camera_type } = toRefs<any>(proxy?.useDict('camera_type'));

const dialog = reactive<any>({
  showUpdate: false,
  showDetail: false,
  showEventRecord: false,
  showSubscribeDevice: false,
  showCreate: false,
  showAdd: false,
  title: ''
});

const cameraInfoList = ref([]);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
let syncCameraLoading = ref(false);

let selectedEquipmentId = ref();
const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  parkId: undefined,
  equipmentId: undefined,
  status: undefined,
  groupId: undefined,
  dataSource: 2,
  params: {}
});

/** 查询摄像头信息列表 */
let startEndTime = ref([]);
const getList = async () => {
  queryParams.value.startDate = startEndTime.value.length > 0 ? parseTime(startEndTime.value[0], '{y}-{m}-{d} 00:00:00') : null;
  queryParams.value.endDate = startEndTime.value.length > 0 ? parseTime(startEndTime.value[1], '{y}-{m}-{d} 23:59:59') : null;

  loading.value = true;
  request({
    url: '/equipment/equipment-info/list',
    method: 'get',
    params: queryParams.value
  }).then((res) => {
    cameraInfoList.value = res.rows;
    total.value = res.total;
  }).finally(() => { loading.value = false; });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  startEndTime.value = []
  queryParams.value = { pageNum: 1, pageSize: queryParams.value.pageSize, dataSource: 2 }

  handleQuery();
};

/** 多选框选中数据 */
const tableSelectionChange = (selection: cameraInfoVO[]) => {
  ids.value = selection.map((item) => item.equipmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查询摄像头信息列表 */
const handleSync = async () => {
  syncCameraLoading.value = true;
  const res = await equipmentSync().finally(() => (syncCameraLoading.value = false));
  proxy?.$modal.msgSuccess(res.msg);

  await getList();
};

const openUpdate = async (row?: any) => {
  selectedEquipmentId.value = row?.equipmentId || ids.value[0];
  dialog.showUpdate = true;
  dialog.title = '修改设备信息';
};
/** 新增按钮操作 */
const openCreate = async () => {
  dialog.showAdd = true;
  dialog.title = '新增设备信息';
};

/** 详情按钮操作 */
const openDetail = async (row?: cameraInfoVO) => {
  selectedEquipmentId.value = row?.equipmentId || ids.value[0];
  dialog.showDetail = true;
  dialog.title = '详情';
};

/** 删除按钮操作 */
const handleDelete = async (row?: cameraInfoVO) => {
  const _equipmentIds = row?.equipmentId || ids.value;
  await proxy?.$modal.confirm('是否确认删除摄像头信息编号为"' + _equipmentIds + '"的数据项？').finally(() => (loading.value = false));
  await request({ url: '/equipment/equipment-info/' + _equipmentIds, method: 'delete' })
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 统计 */
let equipmentStatistic = ref<any>({ totalCount: 0, enableCount: 0, disableCount: 0, nullifyCount: 0 })
let equipmentStatisticLoading = ref(false)
const getEquipmentStatistic = ()=>{
  request({
    url: '/equipment/equipment-info/equipment-online-status-statistic?' + stringify({ dataSourceList: [2] }, { arrayFormat: 'repeat', allowDots: true }),
    method: 'get'
  }).then((res)=> {
    equipmentStatistic.value = res.data
  }).finally(() => equipmentStatisticLoading.value = false)
}

/** 设备分组下拉数据 */
let cameraGroup = ref([])
const getCameraGroupList = async()=>{
  let queryParams = {
    pageNum: 1,
    pageSize: 100
  }
  const res = await request({ url: '/equipment/equipment-camera-group/list', method: 'get', params: queryParams });
  cameraGroup.value = res.rows
}

/**
 * 打开设备上报数据对话框
 */
const openEventRecord = () => {
  dialog.title = '设备上报数据'
  dialog.showEventRecord = true
}

/**
 * 打开告警订阅查询对话框
 */
const openSubscribeDevice = () => {
  dialog.title = '告警订阅设备'
  dialog.showSubscribeDevice = true
}

/** 打开注册回调地址对话框 */
const openRegisterUrl = async () => {
  // 获取注册URL信息
  await getRegisterUrl()

  dialog.showRegisterUrl = true;
  dialog.title = '编辑注册回调地址';
};

/** 查询注册URL信息 */
const registerUrl = ref();
const getRegisterUrl = async () => {
  proxy.$modal.loading('加载中');
  let res = await request({ url: '/equipment/equipment-info/get-register-url', method: 'get' }).finally(() => { proxy.$modal.closeLoading(); });

  registerUrl.value = res.data.wsUri
};

/** 订阅用户与摄像机信息变更 */
const subscribeUserCameraChange = async () => {
  proxy.$modal.loading('订阅中');
  let res = await request({ url: '/open/ivs3800/subscribe-user-camera-change', method: 'post' }).finally(() => { proxy.$modal.closeLoading(); });
  if (res.code == 200) {
    proxy.$modal.msgSuccess('订阅成功');
  } else {
    proxy.$modal.msgError(res.msg);
  }
};

/**
 * 编辑注册回调地址
 */
const registerUrlBtnLoading = ref(false);
const submitRegisterUrl = async () => {
  registerUrlBtnLoading.value = true;
  const res = await request({
    url: '/equipment/equipment-info/regedit-ivs3800-callback?wsUri=' + registerUrl.value,
    method: 'post',
    data: { }
  }).finally(() => { registerUrlBtnLoading.value = false });

  if (res.code == 200) {
    proxy?.$modal.msgSuccess(res.msg);
    dialog.showRegisterUrl = false;
  } else {
    proxy?.$modal.msgError(res.msg);
  }
};

onMounted(() => {
  getList();
  getEquipmentStatistic();
  getCameraGroupList()
});
</script>
<style lang="scss" scoped>
:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.pagination-container) {
  margin-top: 0;
}

p {
  width: 280px;
  padding: 0;
  margin: 0;
}

.ldian {
  margin-right: 10px;
  font-weight: 400;
  color: #51d351;
}

.hdian {
  margin-right: 10px;
  font-weight: 400;
  color: #ff9900;
}

.gzdian {
  margin-right: 10px;
  font-weight: 400;
  color: #fb6260;
}

.label {
  height: 40px;
  font-weight: bold;
  font-size: 18px;
  display: flex;
  align-items: center;

  &:before {
    margin-right: 8px;
    content: '';
    width: 5px;
    height: 17px;
    display: inline-block;
    background-color: #0058f6;
    border-radius: 66px 66px 66px 66px;
  }
}
p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
